﻿using mediaControl.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace mediaControl.Views
{
    /// <summary>
    /// ScreenList.xaml 的交互逻辑
    /// </summary>
    public partial class ScreenList : UserControl
    {
        public ScreenList()
        {
            InitializeComponent();
            Loaded += ScreenList_Loaded;
        }

        private void ScreenList_Loaded(object sender, RoutedEventArgs e)
        {
            if (DataContext is ScreenListViewModel viewModel)
            {
                viewModel.ListBox = listBox;
            }
        }

        private void ListBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            ListBox listBox = sender as ListBox;
            if (listBox != null)
            {
                int index = -1;
                //使用SelectedIndex属性获取鼠标所在的行号


                //index = listView.SelectedIndex;
                if (index == -1)
                {
                    //如果SelectedIndex属性获取失败，则使用HitTest方法获取鼠标所在的行号
                    var hitTest = VisualTreeHelper.HitTest(listBox, e.GetPosition(listBox));
                    if (hitTest != null)
                    {
                        var item = VisualTreeHelper.GetParent(hitTest.VisualHit);
                        while (item != null && !(item is ListBoxItem))
                        {
                            item = VisualTreeHelper.GetParent(item);
                        }
                        if (item != null)
                        {
                            
                            index = listBox.ItemContainerGenerator.IndexFromContainer(item);
                        }
                    }
                }
                //选中该行
                listBox.SelectedIndex = index;
                if (index >= 0 && index < listBox.Items.Count)
                {
                    ListBoxItem item = (ListBoxItem)listBox.ItemContainerGenerator.ContainerFromIndex(index);
                    item.IsSelected = true;
                    // 现在item就是您通过下标获取的ListViewItem
                    listBox.SelectedItem = item;

                }
                else
                {
                    // 索引超出范围，处理错误情况
                }
            }
        }
    }
}
